﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MongoDB.Driver;
using MongoDB.Bson;
using FluentMongo.Linq;

namespace Props.Backend
{
    public abstract class RepositoryBase
    {
        protected string connString = "mongodb://localhost";
        protected string dbName = "Propiedades";

        private MongoServer _server;
        private MongoDatabase _database;

        public RepositoryBase()
        {
            _server = MongoServer.Create(connString);
            _database = _server.GetDatabase(dbName);
        }

        protected MongoCollection<T> GetCollection<T>(string name)
        {
            return _database.GetCollection<T>(name);
        }


    }

    public abstract class RepositoryBase<T> : RepositoryBase
            where T : BaseEntity
    {
        protected abstract string CollectionName { get; }

        MongoCollection<T> _elements = null;
        MongoCollection<T> elements
        {
            get
            {
                if (_elements == null)
                    _elements = GetCollection<T>(CollectionName);

                return _elements;
            }
        }

        public T GetById(string id)
        {
            ObjectId _id = new ObjectId(id);

            return elements.FindOneById(_id);
        }

        public IQueryable<T> Get()
        {
            return elements.AsQueryable();
        }

        public IEnumerable<T> Get(Func<T, bool> predicate)
        {
            return Get().Where(predicate);
        }

        public void Save(T entity)
        {
            if (entity.Id == ObjectId.Empty)
                elements.Insert(entity, SafeMode.True);
            else
                elements.Save(entity, SafeMode.True);
        }

        public void Delete(T entity)
        {
            elements.Remove(new QueryDocument(new BsonElement("_id", entity.Id)));
        }
    }
}
